// pages/details/details.js
const app = getApp()
var detailsData = require("../detailsdata/detailsdata.js");
var usedata = require("../addressdata/addressdata.js");
// const util = require('../../utils/util.js')
const jisuan = require('../../utils/jisuan.js')

var commodityBtn = true; //展开收起
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gwcsl: 0,
    spinfo: "",
    model: '',
    /**
     * dn:mints(n,-1,-2),jsmodel(JINE，TIANSHU),isjzrq(选择截止日期),pstype(0同送，1轮送),
     * zhouqi(0天天订，1单双日订，2周一至周五，3周末订)
     * Count,qdrq,tdrq,jgts,dsj,TotalDays,TotalCount,je,
     * xq1,xq2,xq3,xq4,xq5,xq6,xq7
     */
    dn: {
      mints: 0,
      ishuodong: false,
      ists: true,
      isksrq: false,
      isjzrq: false,
      pstype: "0",
      zhouqi: "0",
      Count: 1,
      qdrq: "",
      tdrq: "",
      snsd: 2,
      jgts: 0,
      dsj: 0,
      TotalDays: 0,
      TotalCount: 0,
      je: 0,
      xq1: 0,
      xq2: 0,
      xq3: 0,
      xq4: 0,
      xq5: 0,
      xq6: 0,
      xq7: 0,
      onsale: "", //选择的活动项
      dnmodel: ""
    },
    quantity1: {
      quantity: 1,
      min: 1,
      max: 20,
      delStatus: 'disabled',
      addStatus: 'normal'
    },
    isLike: true,
    showDialog: false,
    imgUrls: '', //轮播图
    current: 0,
    swiperCurrent: 0,
    discountBtn: true, //是否有优惠券
    popupBtn: "true", //弹出框
    specification: "", //产品规格,
    commodityDetails: "", //商品详情规格
    commodityBtn: true, //展开收起
    commodityDetailsImg: "", //产品详情图片
    dnTs: "", //选择订奶天数
    milkingSelectDay: "",
    zhouqiSelect: 0,
    psrqSelect: false,
    milkingTimer: "", //送奶时间
    // snsd: "",
    syspars: "", //系统参数
    onsaleinfo: "", //活动,20200214代金券
    onsaleselected: "", //选择的活动项
    shoppingcart: true,
    noBuyBtn: false, //不可购买开关
    hdindex: '', //代金券序列号
    hdindex2: '', //默认代金券序列号
    cashCouponText: "", //代金券内容
    giftBtn: false, //代金券默认开关
    giftImgBtn: false, //代金券true or文字false开关

    selectionCapacity: '', //20200219产品规格
    capacitySelect: 0,
    dnmodel_note: jisuan.dnmodel[0].note,
    onsale_note: '',
    mydjq: '',
    spellListLive:1, //20200730，1拼团按钮2订购购买按钮3下架
    spellList: '',
    spellListBtn: true, //拼单显示隐藏
    participateBtn: true, //参与拼单显示隐藏
    pinzhuName: '',
    pinzhuImg: '',
    pinzhuNum: '',
    pinzhuTime: '',
    countDownList: [],
    actEndTimeList: [],
    pinzhuTimeIndex: 0,
    endTimeListEndAll: '2020-12-11 16:51:43',
    spellListTimeAll: '23:49:27',
    spellListAllBtn: false,//拼团过期false
    showModalStatusShare: false,
    shareImgwxHidden: true, //分享图
    openSet: true,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    cancel_userinfo_permission: true,
    canvasWidth: 500, //20200327海报
    canvasHeight: 886,
    maImg: '../images/assets/images/erweima.png', // 小程序码
    avatarUrl: '../images/assets/images/logo.png', // 默认头像
    hImg: '../images/assets/images/bgmg.png', // 商品背景图
    haibaospimg: '',
    productlistShare: {
      'unit': '￥',
      "price": '120.00-1080.00',
      "name": "百香果耶粒酸奶（月套餐每天配送）济南",
      'img': ''
    },
    deliveryMethod:'',//配送方式20200427
    deliveryMethodSelect: '',//20200427
    historicalOrders:'',//历史订单20200427
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    text: '您今天的配送：鲜奶1瓶，尚有1瓶带配送，订单预计截止日期为2020-09-08',
    marqueePace:0.8,//滚动速度
    marqueeDistance:0.8,//初始滚动距离
    marqueeDistance2:0.8,
    marquee2copy_status: false,
    marquee2_margin: 0,
    size: 14,
    orientation: 'left',//滚动方向
    interval: 20, // 时间间隔
    // formSumbitBtn:true,//是否true有确认订单
    // formSumbitHidden:true,//表单false显示true隐藏
    formGouwuche: true,//加入购物车true,直接购买false
    modeBorderClick:true,//到期提醒true隐藏，显示隐藏
    modeBorderClick1: true,//到期提醒true隐藏，显示隐藏
    tipsContent: '最早2020-11-25下单，两天后(2020年11月27日)送到您家。',//提示信息
    tipsHide:false,//提示信息显示隐藏，false显示
    tipsHide1: false,//提示信息显示隐藏，false显示
    addressSelectBtn:true,//选择地址显示隐藏，true隐藏
    addressAll: "",
    addressSelect: "",
    addressText: "",
    addressTextPs:'',//配送地址
    mengShowOrder: false,//下一步蒙层的显示与否
    aniStyle: true,  //动画效果，默认slideup
    aniStyleBlack: true,//遮罩显示隐藏
    tuijianData:'',//推荐日期选择
    tuijianDataIndex:'',//推荐日期下标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // console.log(app.globalData.userInfo)
    // var spinfo = JSON.parse(options.spinfo);
    // console.log(spinfo);
    // var djq = false;
    // var hds = ["HD009"];
    // if (hds.indexOf(spinfo.sp.hddm) >= 0) djq = true;
    // wx.request({
    //   url: app.globalData.ApiUrl + 'GetDinggouSettingSnsd',
    //   data: {
    //     nzid: app.globalData.nzid,
    //     spid: spinfo.sp.spid
    //   },
    //   header: {
    //     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    //   },
    //   method: 'GET',
    //   dataType: 'json',
    //   success: function (res) {
    //     //console.log(res.data);
    //     that.setData({
    //       milkingTimer: res.data,
    //       'dn.snsd': res.data[1].snsd
    //     })
    //   }
    // })
    // if (djq) {
    //   wx.request({
    //     url: app.globalData.ApiUrl + 'GetMydjq',
    //     data: {
    //       comid: app.globalData.nzid,
    //       openid: app.globalData.openid
    //     },
    //     header: {
    //       "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    //     },
    //     method: 'GET',
    //     dataType: 'json',
    //     success: function (res) {
    //       // console.log(res.data);
    //       that.setData({
    //         mydjq: res.data,
    //       })
    //       that.dnJisuan()
    //     }
    //   })
    // }

    // wx.request({
    //   url: app.globalData.ApiUrl + 'SpDetailViewModel',
    //   data: {
    //     nzid: app.globalData.nzid,
    //     spid: spinfo.sp.spid
    //   },
    //   header: {
    //     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    //   },
    //   method: 'GET',
    //   dataType: 'json',
    //   success: function (res) {
    //     console.log(res.data);
    //     that.setData({
    //       commodityDetails: res.data,
    //     })
    //   }
    // })

    // var dnmodel = spinfo.syspars.mints > 1 ? jisuan.dnmodel : jisuan.dnmodel_onlyone
    this.setData({
      // spinfo: spinfo,
      spinfo:detailsData.spinfo,
      syspars: detailsData.spinfo.syspars,
      dnTs: detailsData.spinfo.dnTs,
      // 'dn.dsj': spinfo.price,
      // 'dn.mints': spinfo.syspars.mints,
      // 'dn.TotalDays': Number(spinfo.syspars.mints),
      // 'dn.qdrq': spinfo.syspars.minksrq,
      // //推荐消息， 订奶列表数据
      // imgUrls: [spinfo.sp.productImg, spinfo.sp.productImg, spinfo.sp.productImg],
      // specification: spinfo,
      commodityDetails: detailsData.commodityDetails,
      commodityDetailsImg: detailsData.commodityDetailsImg,
      // dnTs: util.dnTs,
      model: detailsData.spinfo.model,
      // milkingSelectDay: spinfo.syspars.mints > 1 ? util.dnTs[0].milkingDay : 1,
      // 'dn.dnmodel': dnmodel[0],
      // 'dn.zhouqi': dnmodel[0].zhouqi,
      // zhouqiSelect: Number(dnmodel[0].zhouqi),
      imgUrls: detailsData.imgUrls,
      dnmodel_note: detailsData.spinfo.dnmodel_note,
      onsale_note: detailsData.spinfo.onsale_note,
      // specification: detailsData.specification,
      // commodityDetails: detailsData.commodityDetails,
      // commodityDetailsImg: detailsData.commodityDetailsImg,
      // milkingArr: detailsData.milkingArr,
      milkingTimer: detailsData.milkingTimer,
      milkingTimerText: detailsData.milkingTimer[0],
      milkingSelectDay: detailsData.spinfo.dnTs[0].milkingDay,
      // vouchers: detailsData.vouchers,
      // giftPrice1: detailsData.vouchers[0].giftPrice,  
      // 20200219产品规格
      selectionCapacity: detailsData.selectionCapacity,
      // capacitySelect: spinfo.sp.spid,     
      spellList: detailsData.spellList, //20200310拼单
      deliveryMethod:detailsData.deliveryMethod,//20200427配送方式
      deliveryMethodSelect: detailsData.deliveryMethod[0].deliveryMethod,
      historicalOrders: detailsData.historicalOrders,
      // 20201204选择地址
      addressAll: usedata.address,
      addressSelectText: usedata.address[0].index,   
      addressTextPs: usedata.address[0].address,   
      // 20210311推荐日期
      tuijianData: detailsData.tuijianData,
      tuijianDataIndex: detailsData.tuijianData[0].tuijianDataIndex,
    });
    //生成海报价格
    // if(spinfo.syspars.mints=="1"){
    //   this.setData({      
    //     'productlistShare.price': spinfo.price + '/'+spinfo.bzdw, 
    //     'productlistShare.name': spinfo.sp.name + ' （单次配送）',
    //   })
    // }else{
    //   this.setData({
    //     'productlistShare.price': spinfo.priceSumday.toFixed(2) + '/月', 
    //     'productlistShare.name': spinfo.sp.name + ' （每天送到家）',
    //   })
    // }

    let endTimeList = [];
    // 将活动的结束时间参数提成一个单独的数组，方便操作
    this.data.spellList.forEach(o => {
      endTimeList.push(o.endTime)
    })
    this.setData({
      actEndTimeList: endTimeList
    });
    console.log(this.data.actEndTimeList)
    // 列表倒计时函数
    this.countDown();
    // 拼单按钮倒计时
    this.countDownAll();

    // wx.request({
    //   url: app.globalData.ApiUrl + 'GetGwcsl',
    //   data: {
    //     nzid: app.globalData.nzid,
    //     openid: app.globalData.openid
    //   },
    //   header: {
    //     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    //   },
    //   method: 'GET',
    //   dataType: 'json',
    //   success: function (res) {
    //     console.log(res.data);
    //     that.setData({
    //       gwcsl: res.data.gwcsl,
    //     })
    //   }
    // })

    // wx.getSystemInfo({
    //   success: function (res) {
    //     that.setData({
    //       coverHeight: 415, // res.windowHeight,
    //       coverWidth: 286, // res.windowWidth,
    //       cover: app.globalData.url + "TsdXcx/img/share/" + app.globalData.comid + "/" + that.data.spinfo.sp.spid + ".jpg",
    //       shareImg: app.globalData.url + "TsdXcx/img/share/" + app.globalData.comid + "/" + that.data.spinfo.sp.spid + ".jpg",
    //     });

    //   },
    // })

    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
              // 根据自己的需求有其他操作再补充
              // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
              wx.login({
                success: res => {
                  // 获取到用户的 code 之后：res.code
                  console.log("用户的code:" + res.code);
                  // 可以传给后台，再经过解析获取用户的 openid
                  // 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
                  // wx.request({
                  //     // 自行补上自己的 APPID 和 SECRET
                  //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
                  //     success: res => {
                  //         // 获取到用户的 openid
                  //         console.log("用户的openid:" + res.data.openid);
                  //     }
                  // });
                }
              });
            }
          });
        } else {
          // 用户没有授权
          // 改变 isHide 的值，显示授权页面
          that.setData({
            isHide: true
          });
        }
      }
    });
    this.tipsHide('最早2020-11-25下单，两天后(2020年11月27日)送到您家。')//20201126提示信息引用
  },

  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      // 获取到用户的信息了，打印到控制台上看下
      console.log("用户的信息如下：");
      console.log(e.detail.userInfo);
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      that.setData({
        isHide: false
      });
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },

  timeFormat(param) { //小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },

  countDown() { //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.actEndTimeList;
    let countDownArr = [];
    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let arr = o.split(/[- :]/);
      let nndate = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
      nndate = Date.parse(nndate)
      let endTime = nndate;
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        // let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time / 3600);
        let min = parseInt(time % 3600 / 60);
        let sec = parseInt(time % 60);
        obj = {
          spellListTime: this.timeFormat(hou) + ":" + this.timeFormat(min) + ":" + this.timeFormat(sec),
          spellListhideen: false
        }
      } else { //活动已结束，全部设置为'00'
        obj = {
          spellListTime: '00:00:00',
          spellListhideen: true

        }
      }
      countDownArr.push(obj);

    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    var spellList = this.data.spellList;
    for (let i = 0; i < spellList.length; i++) {
      spellList[i].spellListTime = countDownArr[i].spellListTime;
      spellList[i].spellListhideen = countDownArr[i].spellListhideen;
      var pinzhuTimeIndex = this.data.pinzhuTimeIndex;
      var pinzhuTime = countDownArr[pinzhuTimeIndex].spellListTime
      this.setData({
        spellList: spellList,
        pinzhuTime: pinzhuTime
      })
    }
    setTimeout(this.countDown, 1000);
  },

  dnJisuan: function () {
    var dn = jisuan.JisuanModel(this.data.dn);
    console.log("计算结果：");
    console.log(dn);
    this.setData({
      dn: dn
    });
    this.show_mydjq_note()
  },
  onShow: function (e) {
    console.log(this.data.mydjq)
    this.dnJisuan()
    // 页面显示
    var vm = this;
    var length = vm.data.text.length * vm.data.size;//文字长度
    var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
    vm.setData({
      length: length,
      windowWidth: windowWidth,
      marquee2_margin: length < windowWidth ? windowWidth - length : vm.data.marquee2_margin//当文字长度小于屏幕长度时，需要增加补白
    });
    vm.run1();// 水平一行字滚动完了再按照原来的方向滚动
    vm.run2();// 第一个字消失后立即从右边出现
  },
  run1: function () {
    var vm = this;
    var interval = setInterval(function () {
      if (-vm.data.marqueeDistance < vm.data.length) {
        vm.setData({
          marqueeDistance: vm.data.marqueeDistance - vm.data.marqueePace,
        });
      } else {
        clearInterval(interval);
        vm.setData({
          marqueeDistance: vm.data.windowWidth
        });
        vm.run1();
      }
    }, vm.data.interval);
  },
  run2: function () {
    var vm = this;
    var interval = setInterval(function () {
      if (-vm.data.marqueeDistance2 < vm.data.length) {
        // 如果文字滚动到出现marquee2_margin=30px的白边，就接着显示
        vm.setData({
          marqueeDistance2: vm.data.marqueeDistance2 - vm.data.marqueePace,
          marquee2copy_status: vm.data.length + vm.data.marqueeDistance2 <= vm.data.windowWidth + vm.data.marquee2_margin,
        });
      } else {
        if (-vm.data.marqueeDistance2 >= vm.data.marquee2_margin) { // 当第二条文字滚动到最左边时
          vm.setData({
            marqueeDistance2: vm.data.marquee2_margin // 直接重新滚动
          });
          clearInterval(interval);
          vm.run2();
        } else {
          clearInterval(interval);
          vm.setData({
            marqueeDistance2: -vm.data.windowWidth
          });
          vm.run2();
        }
      }
    }, vm.data.interval);
  },
  //轮播图的切换事件 
  swiperChange: function (e) {
    //只要把切换后当前的index传给<swiper>组件的current属性即可 
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  //点击指示点切换 
  chuangEvent: function (e) {
    this.setData({
      swiperCurrent: e.currentTarget.id
    })
  },
  shoppingcart: function () { //加入购物车
    this.setData({
      shoppingcart: false
    })
    this.clickme2();
    this.noStock();
    

  },

  orderBtn: function () { //订购
    this.setData({
      shoppingcart: true
    })
    this.clickme2()
    this.noStock();
  },
  noStock: function () { //无库存
    var count = this.data.specification;
    var g = (count.num * this.data.milkingSelectDay)
    if (g > count.stock) {
      this.setData({
        noBuyBtn: true
      })
    } else {
      this.setData({
        noBuyBtn: false
      })
    }
  },
  //点击我显示购买弹出框
  clickme2: function () {
    this.setData({
      popupBtn: 2
    })
    this.showModal();

  },
  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  commodityBtn: function () {
    commodityBtn = !commodityBtn
    this.setData({
      commodityBtn: commodityBtn
    })
  },

  gotoDnmodel: function (e) { //选择天数
    this.setData({
      zhouqiSelect: e.detail.value,
      dnmodel_note: jisuan.dnmodel[e.detail.value].note,
      milkingSelectDay: e.detail.value == 7 ? 1 : this.data.dn.TotalDays,
      'dn.dnmodel': jisuan.dnmodel[e.detail.value],
      'dn.zhouqi': e.detail.value,
      'dn.jgts': e.detail.value == 1 ? 1 : (e.detail.value == 2 ? 2 : (e.detail.value == 3 ? 1 : (e.detail.value == 4 ? 1 : 0))),
    })
    this.countSum();
    this.noStock();
    this.dnJisuan()
  },
  gotoTs: function (e) { //选择天数
    // console.log('radio发生change事件，携带的value值为：', e.detail.value)
    this.setData({
      milkingSelectDay: Number(e.detail.value) > this.data.dn.mints ? e.detail.value : this.data.dn.mints,
      'dn.TotalDays': Number(e.detail.value) > this.data.dn.mints ? e.detail.value : Number(this.data.dn.mints),
      'dn.ishuodong': false,
      'dn.ists': true,
      'dn.isksrq': false,
      'dn.isjzrq': false,
    })
    this.countSum();
    this.noStock();
    this.dnJisuan()
  },
  godeliveryMethod: function (e) { //选择配送方式20200427
    this.setData({
      deliveryMethodSelect: e.detail.value,
    })
  },
  show_mydjq_note: function () {
    var onsale = ''
    var dn = this.data.dn
    var mydjq = this.data.mydjq
    for (let index in mydjq) {
      if (mydjq[index].jsmodel == 'JINE') {
        if (Number(dn.je) >= Number(mydjq[index].dgje) && Number(dn.je) <= Number(mydjq[index].maxdgje)) {
          this.data.onsale_note = mydjq[index].kssj.substring(0, 10) + '至' + mydjq[index].jssj.substring(0, 10) + mydjq[index].note + mydjq[index].dgqje + '元代金券'
          onsale = mydjq[index]
          break
        } else {
          this.data.onsale_note = ''
        }
      } else if (this.data.mydjq[index].jsmodel == 'TIANSHU') {
        if (Number(dn.TotalDays) >= Number(mydjq[index].dgje) && Number(dn.TotalDays) <= Number(mydjq[index].maxdgje)) {
          this.data.onsale_note = mydjq[index].note
          onsale = mydjq[index]
          break
        } else {
          this.data.onsale_note = ''
        }
      }
    }
    this.setData({
      onsale_note: this.data.onsale_note,
      'dn.onsale': onsale,
    })
  },

  add: function (e) {
    // 加
    var count = this.data.specification;
    if (count.num < count.stock) {
      count.num++
    } else {
      count.num == count.stock;
    }
    count.priceSum = (count.num * count.price).toFixed(2);
    this.setData({
      specification: count,
      'dn.Count': count.num
    });
    this.countSum();
    this.noStock();
  },
  minus: function (e) {
    // 减
    var count = this.data.specification;
    if (count.num <= 1) {
      count.num = 1
    } else {
      count.num--;
    }
    count.priceSum = (count.num * count.price).toFixed(2);
    this.setData({
      specification: count,
      'dn.Count': count.num
    })
    this.countSum();
    this.noStock();
  },
  countSum: function () {
    // 总价
    var count = this.data.specification;
    var milkingSelectDay = this.data.milkingSelectDay;
    count.priceSumday = (count.priceSum * milkingSelectDay).toFixed(2);
    this.setData({
      specification: count,
      'dn.je': count.priceSumday
    })
  },
  milkingTimer: function (e) { //选择送奶时间
    //console.log('radio发生change事件，携带的value值为：', e.detail.value)
    this.setData({
      'dn.snsd': e.detail.value
    })
  },

  gotoGwc: function () { //跳转到到购物车结算

    wx.switchTab({
      url: '../shoppingCart/shoppingCart'
    });
  },

  goCashCoupon: function () { //跳转到代金券页面
    wx.navigateTo({
      url: '../cashCoupon/cashCoupon'
    })
  },

  goZhiFu: function () { //跳转到支付
    wx.redirectTo({
      url: '../pay/pay?dn=' + JSON.stringify(this.data.dn) + '&sp=' + JSON.stringify(this.data.spinfo.sp)
    })
  },
  gotoKsrq: function (e) { //20200213获取开始日期
    var ksrq = e.detail.value
    var jsrq = jisuan.DateAdd('day', this.data.milkingSelectDay, ksrq) //this.data.dn.tdrq
    // if (ksrq > jsrq) {
    //   wx.showToast({
    //     title: '抱歉，配送开始日期不能大于结束日期！',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   e.detail.value = this.data.dn.qdrq
    // }
    this.setData({
      'dn.qdrq': e.detail.value,
      'dn.tdrq': jsrq,
      'dn.ishuodong': false,
      'dn.ists': false,
      'dn.isksrq': true,
      'dn.isjzrq': false,
      //years: e.detail.value.substring(0, 4),
      //months: e.detail.value.substring(5, 7),
      //days: e.detail.value.substring(8, 11)
    })
    this.dnJisuan()
  },
  gotoJzrq: function (e) { //20200214获取结束日期
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    var jsrq = e.detail.value
    var dnts = Number(-this.data.spinfo.syspars.mints)
    var ksrq = jisuan.DateAdd('day', dnts, jsrq)
    console.log(ksrq)
    if (jisuan.GetDateObject(this.data.spinfo.syspars.minksrq) > ksrq) {
      wx.showToast({
        title: '抱歉，配送开始日期不能大于结束日期！',
        icon: 'none',
        duration: 2000
      })
      e.detail.value = jisuan.formatDate(jisuan.DateAdd('day', Number(this.data.spinfo.syspars.mints), this.data.spinfo.syspars.minksrq))
    }

    this.setData({
      'dn.tdrq': e.detail.value,
      'dn.ishuodong': false,
      'dn.ists': false,
      'dn.isksrq': false,
      'dn.isjzrq': true,
    })
    this.dnJisuan()
    this.setData({
      milkingSelectDay: this.data.dn.TotalDays,
    })
  },
  gotoPsrq: function () {
    this.setData({
      psrqSelect: this.data.psrqSelect ? false : true,
    })
  },

  onShareAppMessage: function () { //发给朋友
    return {
      title: this.data.spinfo.sp.name,
      //desc: this.data.spinfo.sp.name,
      path: '/pages/details/details?spinfo=' + JSON.stringify(this.data.specification), // 路径，传递参数到指定页面。
      imageUrl: app.globalData.url + "TsdXcx/img/share/" + app.globalData.comid + "/" + this.data.spinfo.sp.spid + ".jpg",
    }
  },
  //20200214点击我显示代金券，活动
  gotoOnsalse: function () {
    var that = this
    if (this.data.spinfo.sp.hddm.length > 0)
      wx.request({
        url: app.globalData.ApiUrl + 'GetHuodong',
        data: {
          nzid: app.globalData.nzid,
          hddm: this.data.spinfo.sp.hddm,
          openid: app.globalData.openid
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        method: 'GET',
        dataType: 'json',
        success: function (res) {
          var data = res.data.length < 10 ? res.data[0] : res.data;
          var sphd = {
            sp: that.data.spinfo.sp,
            onsale: res.data,
          }
          wx.navigateTo({
            url: '../cashCoupon/cashCoupon?sp=' + JSON.stringify(sphd)
          })
        }
      })
    else {
      var sphd = {
        sp: that.data.spinfo.sp,
        onsale: '',
      }
      wx.navigateTo({
        url: '../cashCoupon/cashCoupon?sp=' + JSON.stringify(sphd)
      })
    }
  },
  vouchersRadio: function (e) { //选择代金券
    console.log('radio发生change事件，携带的value值为：', e.detail.value)
    this.setData({
      hdindex: e.detail.value
    })
  },
  giftSelectBtn: function () { //确认代金券金额\搭赠活动天数
    var that = this;
    this.setData({
      giftBtn: true
    })

    if (this.data.giftBtn) {
      this.setData({
        hdindex2: this.data.hdindex,
        cashCouponText: this.data.onsaleinfo[this.data.hdindex].note,
        onsaleselected: this.data.onsaleinfo[this.data.hdindex],
        'dn.onsale': this.data.onsaleinfo[this.data.hdindex],
      })
    }

    console.log(this.data.dn);
    this.dnJisuan();
    this.hideModal();
    this.setData({
      milkingSelectDay: this.data.dn.zhouqi == 7 ? 1 : this.data.dn.TotalDays,
    })
  },
  gotoCapacityl: function (e) { //20200219选择规格
    console.log(e)
    var that = this
    var sp = ''
    for (var i = 0; i < this.data.spinfo.tjsp.length; i++) {
      if (this.data.spinfo.tjsp[i].spid == e.detail.value) {
        sp = this.data.spinfo.tjsp[i]
        break
      }
    }

    var count = this.data.specification;
    // count.stock = this.data.selectionCapacity[e.detail.value].kucunNum;//库存
    that.setData({
      capacitySelect: e.detail.value,
      specification: this.data.spinfo,
      'spinfo.sp': sp,
      'dn.dsj': sp.price,
      'spinfo.price': sp.price,
      // 'dn.TotalDays': Number(spinfo.syspars.mints),
      // 'dn.qdrq': spinfo.syspars.minksrq,
      //推荐消息， 订奶列表数据
      imgUrls: [sp.productImg, sp.productImg, sp.productImg],
    })
    this.countSum();
    this.noStock();
    this.dnJisuan()
  },
  // < !--20200228 -->
  goIndex: function () { //跳转到首页
    wx.switchTab({
      url: '../index/index'
    });
  },

  spellListAll: function () { //显示隐藏
    this.setData({
      spellListBtn: false
    })
  },
  spellListAllHide: function () { //全部拼单显示隐藏
    this.setData({
      spellListBtn: true
    })
  },
  participateHide: function () { //参与拼单隐藏
    var participateBtn = this.data.participateBtn;
    participateBtn = true;
    this.setData({
      participateBtn: participateBtn
    })
  },
  goSpellList: function (e) { //参与拼单显示
    var count = this.data.spellList;
    var index = e.currentTarget.dataset.index;
    count[index].spellListName;
    this.setData({
      participateBtn: false,
      spellListBtn: true,
      pinzhuName: count[index].spellListName,
      pinzhuImg: count[index].spellListImg,
      pinzhuNum: count[index].spellListNum,
      pinzhuTime: count[index].spellListTime,
      pinzhuTimeIndex: index
    });
  },
  countDownAll() { //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.endTimeListEndAll;
    let countDownArr = [];
    // 对结束时间进行处理渲染到页面
    var o = this.data.endTimeListEndAll
    let arr = o.split(/[- :]/);
    let nndate = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
    nndate = Date.parse(nndate)
    let endTime = nndate;
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      // let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time / 3600);
      let min = parseInt(time % 3600 / 60);
      let sec = parseInt(time % 60);
      this.setData({
        spellListTimeAll: this.timeFormat(hou) + ":" + this.timeFormat(min) + ":" + this.timeFormat(sec),
        spellListAllBtn: false
      })
    } else { //活动已结束，全部设置为'00'
      this.setData({
        spellListTimeAll: '00:00:00',
        spellListAllBtn: true
      })
    }
    setTimeout(this.countDownAll, 1000);
  },



  addGwc: function () { //加入购物车确定按钮
    var dn = this.data.dn
    var sp = this.data.spinfo.sp
    var that = this
    //SaveGwcTiantianding41(string nzid, string openid, string dnjson, string spjson)
    wx.request({
      url: app.globalData.ApiUrl + 'SaveGwcTiantianding41',
      data: {
        nzid: app.globalData.nzid,
        openid: app.globalData.openid,
        dnjson: JSON.stringify(this.data.dn),
        spjson: JSON.stringify(this.data.spinfo.sp)
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res)
        that.setData({
          gwcsl: that.data.gwcsl + 1
        })
      }
    })

    // var count = this.data.specification;
    // count.shoppingcartText++;
    // if (count.stock <= 0) {
    //   count.stock == 0;
    //   // 20200219
    //   wx.showToast({
    //     title: '库存不足',
    //     icon: 'success',
    //     duration: 500
    //   })
    // } else {
    //   count.stock = count.stock - (count.num * this.data.milkingSelectDay);
    //   // 20200219

    // }
    // this.setData({
    //   specification: count
    // })
    // this.hideModal();

    wx.showToast({
      title: '已加入购物车',
      icon: 'success',
      duration: 500
    })


  },



  shareBtn: function () {
    this.showModalShare();

  },
  //显示对话框
  showModalShare: function () {

    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()

    this.setData({
      animationDataShare: animation.export(),
      showModalStatusShare: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDataShare: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModalShare: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationDataShare: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDataShare: animation.export(),
        showModalStatusShare: false
      })
    }.bind(this), 200)
  },
  shareImgwxHidden() { //隐藏海报
    this.setData({
      shareImgwxHidden: true
    })

  },



  shareHwq() { //推荐到微信圈子
    if (wx.openBusinessView) {
      wx.openBusinessView({
        businessType: 'friendGoodsRecommend',
        extraData: {
          product: {
            item_code: this.data.spinfo.sp.spid, //物品id 唯一
            title: this.data.spinfo.sp.name, // 物品名称
            image_list: [
              app.globalData.url + "TsdXcx/img/share/" + app.globalData.comid + "/" + this.data.spinfo.sp.spid + ".jpg", // 物品封面
            ]
          },
        },
        success: function (res) {
          if (res.errCode === 0) {
            wx.showToast({
              title: '推荐成功'
            });
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '推荐失败',
            icon: 'none'
          });
        }
      })
    }
  },

  //20200327 绘制canvas
  drawCanvas: function (codeimg) {
    const _this = this;

    const {
      avatarUrl,
      canvasWidth,
      canvasHeight,
      maImg,
      user,
      hImg,
      productlistShare
    } = this.data;
    const ctx = wx.createCanvasContext('canvas');
    const canvas_width = canvasWidth;
    const canvas_height = canvasHeight;
    // 分享图样式
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);

    // 绘制头像
    ctx.save(); // 先保存状态 已便于画完圆再用
    ctx.beginPath(); //开始绘制
    var avatarurl_width = 80; //绘制的头像宽度
    var avatarurl_heigth = 80; //绘制的头像高度
    var avatarurl_x = 27; //绘制的头像在画布上的位置
    var avatarurl_y = 38; //绘制的头像在画布上的位置
    // contex.beginPath(); //开始绘制
    //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
    ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
    ctx.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
    ctx.drawImage(avatarUrl, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片，必须是https图片
    ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    // 绘制大标题
    // wx.loadFontFace({
    //   family: 'PingFangSC-Medium',
    //   source: 'url("https://xcx.tianshangding.net/font/PingFangSC-Medium.ttf")',
    //   success: res => {
    //     console.log('font load success', res)
    //   },
    //   fail: err => {
    //     console.log('font load fail', err)
    //   }
    // })
    ctx.font = '500 22px Microsoft Yahei'; //PingFangSC-Medium

    ctx.setFillStyle("#333333");
    this.dealWords({
      ctx: ctx, //画布上下文 canvasID
      fontSize: '20', //字体大小
      word: this.data.nickName, //需要处理的文字
      maxWidth: 350, //一行文字最大宽度
      x: 124, //文字在x轴要显示的位置
      y: 60, //文字在y轴要显示的位置
      maxLine: 1 //文字最多显示的行数
    })

    // 绘制小标题
    ctx.font = '500 22px PingFangSC-Medium';
    ctx.setFillStyle("#BEBEBE");
    this.dealWords({
      ctx: ctx, //画布上下文 canvasID
      fontSize: '20', //字体大小
      word: '给你推荐了一个好东西', //需要处理的文字
      maxWidth: 350, //一行文字最大宽度
      x: 124, //文字在x轴要显示的位置
      y: 86, //文字在y轴要显示的位置
      maxLine: 1 //文字最多显示的行数
    })

    // 产品背景色
    ctx.drawImage(hImg, 13, 131, 474, 721);

    var spimg;


    // 产品图
    ctx.drawImage(_this.data.haibaospimg, 50, 177, 400, 400);

    // 产品价格单位
    ctx.font = '500 30px PingFangSC - Medium';
    ctx.setFontSize(28);
    ctx.setFillStyle("#FF6238");
    ctx.fillText(productlistShare.unit, 43, 669);//2020407

    // 产品价格
    wx.loadFontFace({
      family: 'DIN - Medium',
      source: 'url("https://xcx.tianshangding.net/font/DIN-Medium.otf")',
      success: res => {
        console.log('font load success', res)
      },
      fail: err => {
        console.log('font load fail', err)
      }
    })
    ctx.font = '500 42px DIN - Medium';
    ctx.setFontSize(40);
    ctx.setFillStyle("#FF6238");
    ctx.fillText(productlistShare.price, 68, 670);
    // 产品名称
    ctx.font = '500 40px PingFangSC-Medium';
    ctx.setFontSize(20);
    ctx.setFillStyle("#333333");
    this.dealWords({
      ctx: ctx, //画布上下文 canvasID
      fontSize: '20', //字体大小
      word: productlistShare.name, //需要处理的文字
      maxWidth: 260, //一行文字最大宽度
      x: 48, //文字在x轴要显示的位置
      y: 742, //文字在y轴要显示的位置
      maxLine: 2 //文字最多显示的行数
    })

    // 小程序码
    ctx.drawImage(codeimg || this.data.maImg, 340, 710, 106, 106);


    // 绘制图片
    ctx.draw(false, function () {
      // 延时生成图片 否则真机测试文字会样式混乱
      setTimeout(() => {
        // 生成图片
        wx.canvasToTempFilePath({
          canvasId: 'canvas',
          success: res => {
            wx.hideLoading();
            _this.createShareImgSuccess(res.tempFilePath);
          },
          fail: () => {
            wx.showToast({
              title: '海报生成失败~',
              icon: 'none'
            });
          }
        })
      }, 300)

    })
  },
  // 创建分享图成功
  createShareImgSuccess: function (tempFilePath) {
    const _this = this;
    this.setData({
      showPoster: true,
      tempShareImg: tempFilePath,
    });
  },
  xiazai: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.tempShareImg,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 500
        })
      }
    })
  },
  // 保存到手机失败
  saveShareImgErr: function () {
    wx.showToast({
      title: '图片保存失败~ ',
      icon: 'none',
      duration: 3000,
    })
  },
  // 关闭海报图片
  closePoster: function () {
    this.setData({
      showPoster: false
    });
  },

  preD: function () {

  },

  dealWords(options) {
    options.ctx.setFontSize(options.fontSize); //设置字体大小
    var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth); //实际总共能分多少行
    var count = allRow >= options.maxLine ? options.maxLine : allRow; //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数

    var endPos = 0; //当前字符串的截断点
    for (var j = 0; j < count; j++) {
      var nowStr = options.word.slice(endPos); //当前剩余的字符串
      var rowWid = 0; //每一行当前宽度    
      if (options.ctx.measureText(nowStr).width > options.maxWidth) { //如果当前的字符串宽度大于最大宽度，然后开始截取
        for (var m = 0; m < nowStr.length; m++) {
          rowWid += options.ctx.measureText(nowStr[m]).width; //当前字符串总宽度
          if (rowWid > options.maxWidth) {
            if (j === options.maxLine - 1) { //如果是最后一行
              options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 8); //(j+1)*18这是每一行的高度        
            } else {
              options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 8);
            }
            endPos += m; //下次截断点
            break;
          }
        }
      } else { //如果当前的字符串宽度小于最大宽度就直接输出
        options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
      }
    }
  },

  createQrcode: function () {
    const that = this;

    wx.getImageInfo({
      src: app.globalData.xcxhttps + "img/haibao/" + app.globalData.comid + "/" + this.data.spinfo.sp.spid + ".jpg", //服务器返回的带参数的小程序码地址
      success: function (res) {
        //res.path是网络图片的本地地址
        that.setData({
          haibaospimg: res.path
        })
        console.log('产品图片')
        console.log(that.data.haibaospimg)
      },
      fail: function (res) {
        //失败回调
      }
    });

    console.log('输出头像')
    console.log(that.data.avatarUrl);
    var access_token;
    //get_access_token(string appid, string secret)
    wx.request({
      url: app.globalData.ApiUrl + 'get_access_token',
      data: {
        appid: app.globalData.appid,
        secret: app.globalData.secret
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;'
      },
      success: function (res) {
        // console.log(res.data);
        access_token = res.data.access_token //返回access_token
        // 生成页面的二维码
        wx.request({
          //注意：下面的access_token值可以不可以直接复制使用，需要自己请求获取
          url: app.globalData.xcxhttps + 'get_xcx_page_qrcode2.php',
          data: {
            access_token: access_token,
            scene: '1',
            path: 'pages/details/details.html?spinfo=' + JSON.stringify(that.data.specification),//'pages/details/details.html?spinfo={"syspars":{"kspsts":"4","minksrq":"2020-03-16","remindText":"23:59前下单，最早4天后(2020-03-16)送到您家。","dghours":"23","dgMinutes":"59","mints":"1"},"sp":{"maxflsl":"8","flxh":"0","spid":"JLBRYSJZ07","number":"3","newText":"","newShow":true,"newShowRed":false,"productImg":"http://www.tianshangding.com/images/Naizhan/JLBRYSJZ/JLBRYSJZ07.jpg","name":"0.09秒鲜活牛乳（200ml袋）","salesVolume":"6","recommendText":"最新产品","recommendShow":false,"bzdw":"箱","hddm":"","note":"","cpgg":"200ml*12袋","price":"36.00"},"tjsp":[{"maxflsl":"8","flxh":"0","spid":"JLBRYSJZ07","number":"3","newText":"","newShow":true,"newShowRed":false,"productImg":"http://www.tianshangding.com/images/Naizhan/JLBRYSJZ/JLBRYSJZ07.jpg","name":"0.09秒鲜活牛乳（200ml袋）","salesVolume":"6","recommendText":"最新产品","recommendShow":false,"bzdw":"箱","hddm":"","note":"","cpgg":"200ml*12袋","price":"36.00"},{"maxflsl":"8","flxh":"0","spid":"JLBRYSJZ06","number":"4","newText":"","newShow":true,"newShowRed":false,"productImg":"http://www.tianshangding.com/images/Naizhan/JLBRYSJZ/JLBRYSJZ06.jpg","name":"悦鲜活","salesVolume":"5","recommendText":"最新产品","recommendShow":false,"bzdw":"箱","hddm":"","note":"","cpgg":"450ml*6","price":"60.00"},{"maxflsl":"8","flxh":"0","spid":"JLBRYSJZ09","number":"5","newText":"","newShow":true,"newShowRed":false,"productImg":"http://www.tianshangding.com/images/Naizhan/JLBRYSJZ/JLBRYSJZ09.jpg","name":"悦鲜活牛乳瓶1-15-450ml","salesVolume":"0","recommendText":"最新产品","recommendShow":false,"bzdw":"箱","hddm":"","note":"","cpgg":"1*15","price":"150.00"},{"maxflsl":"8","flxh":"0","spid":"JLBRYSJZ11","number":"7","newText":"","newShow":true,"newShowRed":false,"productImg":"http://www.tianshangding.com/images/Naizhan/JLBRYSJZ/JLBRYSJZ11.jpg","name":"悦鲜活牛乳瓶1-12-780ml","salesVolume":"0","recommendText":"最新产品","recommendShow":false,"bzdw":"箱","hddm":"","note":"","cpgg":"780ml*12","price":"204.00"}],"bzdw":"箱","stock":1000000,"num":1,"price":"36.00","priceSum":"36.00","priceSumday":1080}',
            avatarUrl: that.data.avatarUrl
            // //这里按照需求设置值和参数   
            // "width": "320",
            // "auto_color": false,
            // "line_color": {
            //   "r": "0",
            //   "g": "0",
            //   "b": "0"
            // },
            // "is_hyaline": false
          },
          method: "POST",
          // responseType: 'arraybuffer', //设置响应类型
          header: {
            'Content-Type': 'application/x-www-form-urlencoded;'
          },
          success(res) {
            // qrimg = wx.arrayBufferToBase64(res.data); //对数据进行转换操作
            // // // qrimg = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(res.data));
            // // /// 拼接请求头，data格式可以为image/png或者image/jpeg等，看需求
            // const base64ImgUrl = "data:image/png;base64," + qrimg.replace(/[\r\n]/g, '');
            const base64ImgUrl = "data:image/png;base64," + res.data;
            that.send_code(base64ImgUrl)
          },
          fail(e) {}
        })
      }

    })

  },
  //将base64图片转网络图片
  send_code(code) {

    const that = this;
    /*code是指图片base64格式数据*/

    //声明文件系统
    const fs = wx.getFileSystemManager();
    //     fs.getSavedFileList({  // 获取文件列表
    //   success(res) {
    //     res.fileList.forEach((val, key) => { // 遍历文件列表里的数据
    //       // 删除存储的垃圾数据
    //       fs.removeSavedFile({
    //         filePath: val.filePath
    //       });
    //     })
    //   }
    // })
    const basepath = `${wx.env.USER_DATA_PATH}`

    //随机定义路径名称
    var times = new Date().getTime();
    var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
    console.log(codeimg)
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: code.slice(22),
      encoding: 'base64',
      success: () => {
        //写入成功了的话，新的图片路径就能用了
        if (codeimg.length == 0 || !codeimg) {
          codeimg = that.data.maImg;
        }
        setTimeout(that.drawCanvas, 500, codeimg);
      },
      fail(res) {
        console.log(res)
        wx.hideLoading();
        wx.showToast({
          title: '正在清理缓存，请稍后...',
          icon: 'none',
        })
        //清理缓存
        fs.readdir({
          dirPath: basepath, /// 获取文件列表
          success(res) {
            console.log(res)
            res.files.forEach((val) => { // 遍历文件列表里的数据
              console.log(val)
              fs.unlink({
                filePath: basepath + '/' + val
              });

            })

          },
          fail(err) {
            console.log(err)
          },
          complete() {


            console.log('complete')

          }

        })
        return (new Error('ERROR_BASE64SRC_WRITE'));
      },

    });
  },
  onGotUserInfo: function (e) {
    var that = this
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          that.hideModalShare();
          that.setData({
            shareImgwxHidden: false,
          })
          wx.showLoading({
            title: '海报生成中...'
          });
          console.log(e.detail.userInfo)
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          var nickName = e.detail.userInfo.nickName

          wx.getUserInfo({
            success(resInfo) {
              console.log(resInfo)
              if (e.detail.userInfo.avatarUrl.length > 0) {

                //下载头像到服务器缓存
                wx.request({
                  url: app.globalData.xcxhttps + 'download_headerimg_to_server.php',
                  data: {
                    comid: app.globalData.comid,
                    avatarUrl: e.detail.userInfo.avatarUrl,
                    openid: app.globalData.openid
                  },
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                  },
                  method: 'POST',
                  dataType: 'json',
                  success: function (res) {
                    console.log(res.data);
                    wx.downloadFile({
                      url: app.globalData.xcxhttps + '/img/headerimg/' + app.globalData.comid + '/' + app.globalData.openid + '.jpg',
                      success(downloadRes) {
                        console.log(downloadRes)
                        if (downloadRes.statusCode === 200) {
                          that.setData({
                            avatarUrl: downloadRes.tempFilePath,
                            nickName: nickName,
                          })
                          that.createQrcode();
                        }
                      },
                    })
                  }
                })


              } else {
                that.setData({
                  avatarUrl: '../images/assets/images/logo.png',
                  nickName: nickName,
                })
                that.createQrcode();
              }

            }
          })


        } else {
          that.setData({
            avatarUrl: '../images/assets/images/logo.png',
            nickName: '天尚订',
          })
          that.createQrcode();
        }
      }
    })
  },

  //取消获得个人信息授权 cancel_userinfo_permission:!hasUserInfo
  cancel_userinfo_permission: function () {
    this.setData({
      cancel_userinfo_permission: true,
    })
  },
  //获得个人微信信息授权
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      hasUserInfo: true,
      cancel_userinfo_permission: true,
    })
    this.goCreateHaibao()
  },

  //点击生成海报
  goCreateHaibao: function (e) {
    this.hideModalShare();
    //是否授权获得用户微信信息
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      this.shareFrends()
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        this.shareFrends()
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          this.shareFrends()
        }
      })
    }
  },
  shareImgwxHidden() { //生成海报
    this.setData({
      // shareImgwxHidden: true, 
      openSet: true
    })
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '海报已保存到相册',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: false
              })
            }
          },
          fail: function (res) {
            console.log(11111)
          }
        })
      }
    })
  },
  goConsumptionDetails: function () {//跳转到消费明细
    wx.navigateTo({
      url: '../consumptionDetails/consumptionDetails'
    })
  },
  goGouwucheForm: function () {
    this.hideModal()
    this.setData({
      mengShowOrder: false,//下一步蒙层的显示与否
      aniStyle: true,  //动画效果，默认slideup
      aniStyleBlack: true,//遮罩显示隐藏
    })
    wx.showToast({
      title: '已加入购物车',
      icon: 'success',
      duration: 500
    })
  },  
  // 确认订单支付隐藏
  goZhiFuFormHide: function () {
    this.setData({
      mengShowOrder: false,//下一步蒙层的显示与否
      aniStyle: true,  //动画效果，默认slideup
      aniStyleBlack: true,//遮罩显示隐藏
    })
  },
  modeBorderClick:function(){//到期提醒显示
    
    this.setData({
      modeBorderClick: false
    })    
  },
  tipsHide:function(a){//提示信息
    var that=this
      that.setData({
        tipsContent: a
      })   
      setTimeout(function () {
        that.setData({
          tipsHide:true
        }) 
      }, 2000)
    },
  modeBorderClick1: function () {//到期提醒显示

    this.setData({
      modeBorderClick1: false
    })
  },
  tipsHide1: function (a) {//提示信息
    var that = this
    that.setData({
      tipsContent: a
    })
    setTimeout(function () {
      that.setData({
        tipsHide1: true
      })
    }, 2000)
  },
  addressRadio: function (e) {//选择默认地址
    console.log('radio发生change事件，携带的value值为：', e.detail.value)
    var count = this.data.addressAll;
    var index = e.detail.value
    var addressTextPs = count[index].address;
    this.setData({
      addressSelectText: e.detail.value,
      addressTextPs: addressTextPs,
    })
  },
  addressRadio2: function (e) {//选择地址
    var count = this.data.addressAll;
    var index = e.currentTarget.dataset.index;
    var addressTextPs = count[index].address;
    this.setData({
      addressTextPs: addressTextPs,
      addressSelectBtn: true
    })
  },
  
  remove: function (e) {
    // 删除
    var count = this.data.addressAll;
    var that = this;
    var mrAddress = that.data.addressSelectText
    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          // 获取要删除数据的id 
          var index = e.currentTarget.dataset.index;
          // 删除数组对应的数据内容 
          var release = count;
          // 获取选中的radio索引
          count.splice(index, 1)


          //判断数据的长度 
          var len = count.length;
          //通过判断数组的长度来决定是否显示隐藏的部分 
          // console.log(count)
          that.setData({
            addressAll: count
          });
        } else if (res.cancel) {
          console.log('用户点击取消删除')
        }
      }

    })
  },
  goEditAddressId: function (event) {
    var newsid = event.currentTarget.dataset.newsid;
    wx.navigateTo({
      url: '../editAddress/editAddress?newsid=' + newsid
      // 跳转到商品详情
    })
  },
  goEditAddress: function () {//跳转地址页面
    wx.navigateTo({
      url: '../editAddress/editAddress'
    })
  },
  addressAllShow: function () {//地址选择显示
    this.setData({
      addressSelectBtn: false
    });
  }, 
  addressAllHide: function () {//地址选择隐藏
    this.setData({
      addressSelectBtn: true
    });
  }, 
  //下一步蒙层的显示
  showMengOrder: function (e) {     
    this.setData({
      mengShowOrder: true,      //蒙层显示
      aniStyleBlack:false,
      aniStyle: true//设置动画效果为slideup
    })
  },
  outbtn: function (e) {      //这是list-fix的点击事件，给它绑定事件，是为了实现点击其它地方隐藏蒙层的效果
    var that = this;
    this.setData({
      aniStyle: false,//设置动画效果为slidedown
      
    })
    setTimeout(function () {    //延时设置蒙层的隐藏，这个定时器的时间，就是slidedown在css动画里设置的时间，这样就能实现slidedown动画完成后，蒙层才消失的效果。不设置定时器会导致动画效果看不见
      that.setData({
        mengShowOrder: false,
        aniStyleBlack: true,
      })
    }, 200)
  },
  inbtn: function (e) {     //这个事件必须有，就算不做什么事情也要写上去，因为这个事件是为了防止事件冒泡，导致点击in-list这里面的元素时，点击事件冒泡到list-fix触发它的slidedown事件。
    console.log("in")
  },
  tuijianData: function (e) { //选择推荐日期选择20210311
    console.log('radio发生change事件，携带的value值为：', e.detail.value)
    this.setData({
      tuijianDataIndex: e.detail.value
    })
  },  
})